// 网络请求封装
const config = require('./config');

function request(options) {
  return new Promise((resolve, reject) => {
    // 获取Token
    const token = wx.getStorageSync('token');
    
    // 构建请求头
    const headers = {
      'content-type': 'application/json'
    };
    
    // 如果有token，添加到Authorization头
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }

    wx.request({
      url: config.serverUrl + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: headers,
      timeout: config.timeout,
      success(res) {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // Token过期或无效，清除本地存储
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          wx.showToast({
            title: '登录已失效，请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
          reject(new Error('未授权'));
        } else {
          reject(new Error('请求失败'));
        }
      },
      fail(err) {
        reject(err);
      }
    });
  });
}

module.exports = {
  get(url, data) {
    return request({ url, method: 'GET', data });
  },
  
  post(url, data) {
    return request({ url, method: 'POST', data });
  },
  
  put(url, data) {
    return request({ url, method: 'PUT', data });
  },
  
  delete(url, data) {
    return request({ url, method: 'DELETE', data });
  }
};


